package org.gesplan.util;

import java.awt.Cursor;
import java.awt.Toolkit;
import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;

/**
 *
 * @author Roger
 */
public class RefreshWorker extends SwingWorker<Void, Void> {

    private JPanel panel;
    private EntityManager entityManager;
    private JProgressBar dbTaskProgressBar;
    private Query query;
    private List<?> listObject;


    public RefreshWorker(JPanel panel, EntityManager entityManager, Query query) {
        this.panel = panel;
        this.entityManager = entityManager;
        this.query = query;
    }


    public RefreshWorker(JPanel panel, EntityManager entityManager, Query query, List<?> listObject) {
        this(panel, entityManager, query);
        this.listObject = listObject;
    }


    public void setList(List<?> listObject) {
        this.listObject = listObject;
    }


    @SuppressWarnings({ "rawtypes", "unchecked" })
    @Override
    public Void doInBackground() {
        
        if (dbTaskProgressBar == null) {
            dbTaskProgressBar = Utils.getProgressBar();
        }
        panel.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        dbTaskProgressBar.setValue(0);
        try {
            System.out.println("Refresh.Begin");
            if (entityManager.getTransaction().isActive()) {
                entityManager.getTransaction().rollback();
                dbTaskProgressBar.setValue(200);
                entityManager.getTransaction().begin();
            }
            dbTaskProgressBar.setValue(400);
            Collection data = query.getResultList();
            dbTaskProgressBar.setValue(600);
            for (Object entity : data) {
                entityManager.refresh(entity);
            }
            dbTaskProgressBar.setValue(1000);
            System.out.println("Refresh.Clear");
            listObject.clear();
            dbTaskProgressBar.setValue(5000);
            listObject.addAll(data);
            System.out.println("Refresh.End");
            dbTaskProgressBar.setValue(10000);
        } catch (Exception e) {
        }
        return null;

    }


    @Override
    public void done() {
        Toolkit.getDefaultToolkit().beep();
        dbTaskProgressBar.setValue(0);
        panel.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }
    
    
}